var config = require('../config')
var db = require('../db')
let reConnSerial
let watchSerial
//初始化
var init = () => {
    config.load(() => {
        config.inputEvent.on('add', (data) => {
            if (data == 1) {
                var configInfo = config.getConfigInfo()
                if (configInfo.frame == 'vat') {
                    pulseTrig(2000, 500)
                }
                else pulseTrig(0, 500)
            }
        })
        config.inputEvent.on('delete', (data) => {
            db.deleteLastRecord((err) => {
                console.log(err)
            })
            // console.log('删除')
        })
    })
}

//脉冲触发
//延迟触发时间
//触发保持时间
var pulseTrig = (delayTrig, delayHold) => {
    setTimeout(() => {
        var trigger = config.getTrigPort()
        trigger.write(1).then(
            setTimeout(() => { trigger.write(0) }, delayHold)//延迟后off
        )
        // trigger.writeSync(1)//触发on
        // setTimeout(() => { trigger.writeSync(0) }, delayHold)//延迟后off
    }, delayTrig)
}

//配置信息已写入
config.configEvent.on('configed', () => {
    console.log('触发开启')
    var serialPort = config.getSerialPort()
    // console.log(serialPort)
    if (!serialPort.isOpen)
        openSerial()
})

//开启串口
var openSerial = () => {
    var serialPort = config.getSerialPort()
    var frame = config.getFrame()
    serialPort.open((err) => {
        if (err) {
            if (!reConnSerial || reConnSerial.isWorking == false)
                startReconnSerial()
            // if(!reconnS.isWorking)
            // reconnS.start()
            // console.log('failed to open: ' + err);
        } else {
            console.log('open serialport');
            if (reConnSerial && reConnSerial.isWorking)
                stopReconnSerial()
            if (!watchSerial || !watchSerial.isWorking)
                watchSerialFn()
            // if(reconnS.isWorking)
            // reconnS.stop()
            var parser = frame.parserRule(serialPort)
            parser.on('data', (data) => {
                var str = data.toString()
                console.log(str)
                var obj = frame.resolve(str)
                // console.log(obj)
                if (obj.status) {
                    db.insertRecord(obj.data, (err) => {
                        console.log(err)
                    })
                }
                else
                    console.log(obj.msg)
            })
        }
    })
}

//开始重连串口
var startReconnSerial = () => {
    reConnSerial = setInterval(() => {
        // console.log(reConnSerial)
        reConnSerial.isWorking = true
        openSerial()
    }, 2000)
}

//停止重连串口
var stopReconnSerial = () => {
    clearInterval(reConnSerial)
    reConnSerial.isWorking = false
    // console.log(reConnSerial)
}

//串口断线监测
var watchSerialFn = () => {
    watchSerial = setInterval(() => {
        watchSerial.isWorking = true
        var serialPort = config.getSerialPort()
        // console.log(serialPort.isOpen)
        //如果串口断开同时重连服务没有初始化或开启
        if (!serialPort.isOpen && (!reConnSerial || !reConnSerial.isWorking)) {
            startReconnSerial()//开启重连方法
            clearInterval(watchSerial)//关闭断线监测
            watchSerial.isWorking = false
        }
    }, 2000);
}

module.exports = {
    init,
    openSerial
}